package com.module.init;

import java.rmi.RemoteException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;

import com.module.admin.rest.rmi.data.ServerDataCenterServiceImpl;
import com.module.admin.rest.rmi.service.RestDataService;
import com.module.admin.rest.rmi.service.impl.RestDataServiceImpl;
import com.module.admin.sys.enums.SysConfigCode;
import com.module.admin.sys.service.SysConfigService;
import com.module.comm.constants.ConfigCons;
import com.module.comm.constants.Constant;
import com.module.comm.constants.DictCons;
import com.module.monitor.TaskManager;
import com.system.comm.utils.FrameSpringBeanUtil;
import com.system.comm.utils.FrameTimeUtil;
import com.system.rmi.RmiConsumer;
import com.system.rmi.RmiProvider;
import com.system.rmi.service.DataCenterService;

/**
 * 初始化系统数据的Servlet
 * @author duanbin
 * @date 2016-5-16 下午9:54:12
 * @version V1.0.0
 */
public class Init extends HttpServlet {

	private static final Logger LOGGER = Logger.getLogger(Init.class);

	private static final long serialVersionUID = -2274726206362496315L;

	/**
	 * 初始化方法
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		LOGGER.info("初始化数据中...");
		long startTime = System.currentTimeMillis();
		Constant.webroot = config.getServletContext().getContextPath();
		config.getServletContext().setAttribute("webroot", Constant.webroot);
		//版本号为年月日[如: 20130126]
		String version = String.format("?version=%s", FrameTimeUtil.parseString(FrameTimeUtil.getTime(), FrameTimeUtil.FMT_YYYYMMDDHH));
		config.getServletContext().setAttribute("version", version);
		config.getServletContext().setAttribute("projectName", ConfigCons.projectName);

		SysConfigService configService = FrameSpringBeanUtil.getBean(SysConfigService.class);
		config.getServletContext().setAttribute("prjFilePath", configService.getValue(SysConfigCode.PRJ_FILE_PATH));

		Constant.realpath = config.getServletContext().getRealPath("");

		DictCons.init(config.getServletContext());

		//初始化任务
		new TaskManager().init();

		//初始化rmi
		try {
			
			DataCenterService data = FrameSpringBeanUtil.getBean(ServerDataCenterServiceImpl.class);
			
			RmiProvider provider = new RmiProvider(data);
			//发布数据中心的RMI服务
			provider.publishDataCenter(ConfigCons.serverRmiHost, ConfigCons.serverRmiPort);
			
			//发布接口统计
			RestDataService restDataService = new RestDataServiceImpl();
			provider.publish(restDataService, ConfigCons.restRmiHost, ConfigCons.restRmiPort);
			

			//初始化客户端的数据中心
			RmiConsumer.init(ConfigCons.getRmiServers());

			LOGGER.info("初始rmi服务成功!");
		} catch (RemoteException e) {
			LOGGER.info("初始rmi异常: " + e.getMessage(), e);
			throw new ServletException(e.getMessage(), e);
		}

		LOGGER.info("初始化资源花费" + (System.currentTimeMillis() - startTime) + "毫秒!");
	}

}
